package net.easyjava.base.service.mongodb.impl;

import com.google.code.morphia.query.UpdateOperations;
import net.easyjava.base.Exception.MongoException;
import net.easyjava.base.bean.mongodb.ArticleDataBean;
import net.easyjava.base.dao.mongodb.ArticleDataDao;
import net.easyjava.base.service.mongodb.ArticleDataService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * Created by wxnacy on 16/1/8.
 */
@Component
public class ArticleDataServiceImpl implements ArticleDataService {
    @Resource
    private ArticleDataDao articleDataDao;
    /**
     * 保存
     *
     * @param articleDataBean
     * @return
     */
    @Override
    public ArticleDataBean save(ArticleDataBean articleDataBean) throws MongoException{
        if(articleDataBean == null){
            throw new NullPointerException("articleDataBean can't be null");
        }
        articleDataBean = find((String) articleDataDao.save(articleDataBean).getId());//?find(articleDataBean.getId()):null;
        return articleDataBean;
    }

    /**
     * 查找
     *
     * @param articleId
     * @return
     */
    @Override
    public ArticleDataBean find(String articleId) throws MongoException{
        return articleDataDao.findOne("articleId",articleId);
    }

    /**
     * 修改
     *
     * @param articleDataBean
     * @return
     */
    @Override
    public ArticleDataBean update(ArticleDataBean articleDataBean) throws MongoException{
        if(articleDataBean == null){
            throw new NullPointerException("articleDataBean can't be null");
        }
        UpdateOperations<ArticleDataBean> operations = articleDataDao.createUpdateOperations();

        if(articleDataBean.getClickCount()>0){
            operations.set("clickCount", articleDataBean.getClickCount());
        }
        if(articleDataBean.getCommentCount()>0){
            operations.set("commentCount", articleDataBean.getCommentCount());
        }
        if(articleDataBean.getViewCount()>0){
            operations.set("viewCount", articleDataBean.getViewCount());
        }
        if(articleDataBean.getPraiseCount()>0){
            operations.set("praiseCount", articleDataBean.getPraiseCount());
        }
        if(articleDataBean.getUpdateCount()>0){
            operations.set("updateCount", articleDataBean.getUpdateCount());
        }
        if(articleDataBean.getTotalViewTime()>0){
            operations.set("totalViewTime", articleDataBean.getTotalViewTime());
        }
        operations.set("updateTime",System.currentTimeMillis());
        articleDataDao.updateFirst(articleDataDao.createQuery().filter("id", articleDataBean.getId()), operations);
        return null;
    }

    /**
     * 通过文章id查找
     *
     * @param articleId
     * @return
     * @throws MongoException
     */
    @Override
    public ArticleDataBean findByArticleId(String articleId) throws MongoException {
        return articleDataDao.findOne("articleId",articleId);
    }
}
